<template>
  <div class>
    <PageTitle :title="pageTitle"></PageTitle>
    <div class="form-wrapper">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="快速添加" v-if="$route.params.id == 'none'">
          <el-button type="primary" @click="quickAdd">添加</el-button>
        </el-form-item>
        <el-form-item label="款式名称" prop="goods_name">
          <el-input v-model="ruleForm.goods_name" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <!-- <el-form-item label="款式描述" prop="describe">
          <el-input v-model="ruleForm.describe" placeholder="请输入商品描述"></el-input>
        </el-form-item>-->
        <!-- <el-form-item label="商品价格" prop="price">
          <el-input v-model="ruleForm.price" type="number" placeholder="请输入商品价格">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>-->
        <el-form-item label="所属公司" prop="company">
          <el-select v-model="ruleForm.company" placeholder="请选择一级分类" :disabled="disabled1">
            <template v-for="(item, index) in companyArr">
              <el-option :label="item.company" :value="item.id" :key="index"></el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="款式品牌" prop="fication_name">
          <el-select
            v-model="ruleForm.fication_name"
            placeholder="请选择二级分类"
            :disabled="disabled1"
            @change="selectFid"
          >
            <template v-for="(item, index) in ficationArr">
              <el-option :label="item.fication_name" :value="item.fication_name" :key="index"></el-option>
            </template>
          </el-select>
        </el-form-item>
        <!--   <el-form-item label="款式图/视频">
          <el-switch
            v-model="coverType"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="视频"
            inactive-text="图片">
          </el-switch>
        </el-form-item>-->
        <el-form-item label="款式图" prop="coverFileList" v-if="!coverType">
          <Upload
            :fileListArr="ruleForm.coverFileList"
            :fileListName="'coverFileList'"
            :fileMaxCount="1"
            @fileChange="fileChange"
          ></Upload>
        </el-form-item>
        <el-form-item label="款式视频" prop="coverFileList" v-else>
          <UploadVideo
            :fileListArr="ruleForm.coverFileList"
            :fileListName="'coverFileList'"
            :fileMaxCount="1"
            @fileChange="fileChange"
          ></UploadVideo>
        </el-form-item>
        <!-- <el-form-item label="详情图" prop="fileList">
          <Upload
            :fileListArr="ruleForm.fileList"
            :fileListName="'fileList'"
            :fileMaxCount="5"
            @fileChange="fileChange"
          ></Upload>
        </el-form-item>-->
        <!-- <el-form-item label="款式图" prop="openFile">
          <Upload
            :fileListArr="ruleForm.openFile"
            :fileListName="'openFile'"
            :fileMaxCount="1"
            @fileChange="fileChange"
          ></Upload>
        </el-form-item>-->
        <!-- <el-form-item label="未开盒图片" prop="unOpenFile">
          <Upload
            :fileListArr="ruleForm.unOpenFile"
            :fileListName="'unOpenFile'"
            :fileMaxCount="1"
            @fileChange="fileChange"
          ></Upload>
        </el-form-item>-->
        <el-form-item label="库存" prop="stock">
          <el-input type="number" v-model="ruleForm.stock" placeholder="请输入库存" style="width:217px;">
            <template slot="append">个</template>
          </el-input>
        </el-form-item>
        <el-form-item label>
          <span class="tip">如果不在内容中心栏添加视频或者图片 首页不展示</span>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="$router.go(-1)">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import _ from "lodash";
import PageTitle from "@/components/pageTitle/PageTitle.vue";
import Upload from "@/components/upload/Upload.vue";
import UploadVideo from "@/components/uploadVideo/UploadVideo.vue";
export default {
  name: "GoodsDetail",
  components: {
    PageTitle,
    Upload,
    UploadVideo
  },
  activated() {
    this.$goTop();
    this.getCompany();
    this.getFication();
  },
  deactivated() {
    this.$destroy();
  },
  data() {
    return {
      companyFlag: false,
      coverFlag: "",
      companyArr: [],
      ficationArr: [],
      ficationList: [],
      coverType: false,
      ruleForm: {
        goods_name: "",
        price: "",
        describe: "",
        stock: "",
        company: "",
        fication_id: "",
        fication_name: "",
        coverFileList: [], //type: 1 为图片    type: 2 为视频
        fileList: [],
        openFile: [],
        unOpenFile: []
      },
      rules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        describe: [
          { required: true, message: "请输入商品描述", trigger: "blur" }
        ],
        price: [
          { required: true, message: "请输入价格", trigger: "blur" },
          {
            validator(rule, value, callback) {
              const boolean = new RegExp(/^([1-9]\d{0,8}|0)(\.\d{1,2})?$/).test(
                value
              );
              if (!boolean) {
                return callback(new Error("请正确输入商品价格"));
              }
              return callback();
            },
            trigger: "blur"
          }
        ],
        company: [
          { required: true, message: "请选择所属公司", trigger: "change" }
        ],
        fication_name: [
          { required: true, message: "请选择商品品牌", trigger: "change" }
        ],
        coverFileList: [
          { type: "array", required: true, message: "请上传封面" }
        ],
        fileList: [{ type: "array", required: true, message: "请上传详情图" }],
        openFile: [{ type: "array", required: true, message: "请上传款式图" }],
        unOpenFile: [
          { type: "array", required: true, message: "请上传未开盒展示图" }
        ],
        stock: [
          { required: true, message: "库存", trigger: "blur" },
          {
            validator(rule, value, callback) {
              const boolean = new RegExp(/^[0-9][0-9]*$/).test(value);
              if (!boolean) {
                return callback(new Error("请输入正整数"));
              }
              return callback();
            },
            trigger: "blur"
          }
        ]
      }
    };
  },
  watch: {
    company(company) {
      if (this.companyFlag) {
        this.ruleForm.fication_id = "";
        this.ruleForm.fication_name = "";
      }
      this.companyFlag = true;
      this.ficationArr = this.ficationList.filter(item => {
        return company == item.company_id;
      });
    },
    coverType() {
      this.ruleForm.coverFileList = [];
    }
  },
  computed: {
    pageTitle() {
      return this.$route.params.id == "none" ? "款式添加" : "款式详情";
    },
    disabled1() {
      return this.$route.params.id == "none" ? false : true;
    },
    submitUrl() {
      return this.$route.params.id == "none"
        ? this.$api + "/v1/goods/goods"
        : this.$api + "/v1/goods/modify";
    },
    coverFileIdArr() {
      return this.ruleForm.coverFileList[0].id;
    },
    fileIdArr() {
      return this.ruleForm.fileList
        .map(item => {
          return item.id;
        })
        .toString();
    },
    openFileArr() {
      return this.ruleForm.openFile
        .map(item => {
          return item.id;
        })
        .toString();
    },
    unOpenFileArr() {
      return this.ruleForm.unOpenFile
        .map(item => {
          return item.id;
        })
        .toString();
    },
    company() {
      return this.ruleForm.company;
    }
  },
  methods: {
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    quickAdd() {
      let obj = JSON.parse(localStorage.getItem("goodMsg"));
      this.ruleForm.goods_name = obj.goods_name;
      // this.ruleForm.price = obj.price
      this.ruleForm.describe = obj.describe;
      this.ruleForm.stock = obj.stock;
      this.ruleForm.company = obj.company;
      this.ruleForm.fication_id = obj.fication_id;
      this.ruleForm.fication_name = obj.fication_name;
      obj.fileList.forEach(item => {
        this.ruleForm.fileList.push({
          id: item.response.data.id,
          url: item.response.data.url
        });
      });
    },
    // 如果是编辑页，请求数据的函数
    async _get() {
      let {
        data: { code, data }
      } = await this.$axios({
        url: this.$api + "/v1/goods/details",
        method: "GET",
        params: {
          id: this.$route.params.id
        }
      });
      if (code === 0) {
        this.ruleForm.goods_name = data.data.goods_name;
        // this.ruleForm.price = data.data.price
        this.ruleForm.describe = data.data.describe;
        this.ruleForm.stock = data.data.stock;
        this.ruleForm.company = data.data.company;
        this.ruleForm.fication_id = data.data.fication_id;
        this.ruleForm.fication_name = data.data.fication_name;
        data.details.forEach(item => {
          if (item.url) {
            this.coverType = item.url.endsWith("mp4");
            this.$nextTick(() => {
              // 加载封面
              this.ruleForm.coverFileList.push({
                id: item.id,
                url: item.url
              });
            });
          }
        });
        // 加载款式图
        // data.details[0].forEach(item => {
        //   this.ruleForm.openFile.push(item)
        // })
        // 加载未开盒图片
        // data.details[1].forEach(item => {
        //   this.ruleForm.unOpenFile.push(item)
        // })
        // 加载详情图
        // data.details[2].forEach(item => {
        //   this.ruleForm.fileList.push(item)
        // })
      }
    },
    fileChange(data) {
      console.log("上传-------", data);
      this.ruleForm[data.el] = data.arr;
    },
    async getCompany() {
      let {
        data: { data }
      } = await this.$axios({
        url: this.$api + "/v1/company/list",
        method: "GET",
        params: {
          size: 1000,
          current: 1
        }
      });
      this.companyArr = data.items;
    },
    async getFication() {
      let {
        data: { data }
      } = await this.$axios({
        url: this.$api + "/v1/fication/list",
        method: "GET",
        params: {
          size: 1000,
          current: 1
        }
      });
      this.ficationList = data.items;
      if (this.$route.params.id != "none") {
        this._get();
      }
    },
    selectFid() {
      var temp = this.ficationList.filter(res => {
        return res.fication_name == this.ruleForm.fication_name;
      })[0];
      console.log(temp);
      this.ruleForm.fication_id = this.ficationList.filter(res => {
        return res.fication_name == this.ruleForm.fication_name;
      })[0].oid;
      console.log(this.ruleForm.oid);
    },
    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (!valid) {
          return false;
        } else {
          this._submit();
        }
      });
    },
    _submit: _.throttle(
      async function() {
        let {
          data: { code, data }
        } = await this.$axios({
          url: this.submitUrl,
          method: "POST",
          data: {
            goods_name: this.ruleForm.goods_name,
            describe: this.ruleForm.describe,
            // price: this.ruleForm.price,
            company: this.ruleForm.company,
            fication_id: this.ruleForm.fication_id,
            fication_name: this.ruleForm.fication_name,
            open: this.coverFileIdArr,
            // details: this.fileIdArr,
            stock: this.ruleForm.stock,
            //open: this.openFileArr,
            // no: this.unOpenFileArr,
            id: this.$route.params.id
          }
        });
        if (code == 0) {
          this.$message.success(data);
          if (this.$route.params.id == "none") {
            let obj = {
              goods_name: this.ruleForm.goods_name,
              price: this.ruleForm.price,
              describe: this.ruleForm.describe,
              stock: this.ruleForm.stock,
              company: this.ruleForm.company,
              fication_id: this.ruleForm.fication_id,
              fication_name: this.ruleForm.fication_name,
              fileList: this.ruleForm.fileList
            };
            localStorage.setItem("goodMsg", JSON.stringify(obj));
          }
          setTimeout(() => {
            this.$router.go(-1);
          }, 1500);
        }
      },
      2000,
      { trailing: false }
    )
  }
};
</script>

<style lang='scss'>
.form-wrapper {
  width: 50%;
}
.tip {
  color: red;
}
</style>
